package com.mj.mafeed.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.mj.dollars.AppConnect;
import com.mj.mafeed.R;
import com.mj.mafeed.adapter.BannerAdapter;
import com.mj.mafeed.bean.MobileIndexJSON;
import com.mj.mafeed.bean.MobileIndexListJSON;
import com.mj.mafeed.bean.ProductJSON;
import com.mj.mafeed.config.Constants;
import com.mj.mafeed.service.MobileIndexService;
import com.mj.mafeed.service.ProductService;
import com.mj.mafeed.util.HttpUtils;
import com.mj.mafeed.util.SPUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 首页
 * @author zhaominglei
 * @date 2015-11-23
 * 
 */
public class IndexActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = IndexActivity.class.getSimpleName();
	private MobileIndexService mobileIndexService = new MobileIndexService();
	private ProductService productService = new ProductService();
	private boolean isExit = false;
	private TimerTask timerTask;
	//热门产品轮播图
//	private LinearLayout hotLayout;
	private ViewGroup hotViewGroup;
	private ViewPager hotViewpager;
	private ImageView[] hotImageViews;
	private List<String> hotLunboImages = new ArrayList<String>();
	private int hotCurrentItem = 0; // 当前图片下标
	private TextView promotionPriceTxt; //促销价
	private TextView priceTxt; //原价
	private TextView productNameTxt; //产品名称
	private MobileIndexListJSON mobileIndexListJSON;
	private List<ProductJSON> productJSONs = new ArrayList<ProductJSON>();
	private GestureDetector hotGestureDetector;
	private LinearLayout teamLayout; //技术团队
	private LinearLayout aboutLayout; //关于美傲
	private LinearLayout newsLayout; //美傲头条
	private TextView newsTxt; //头条
	//轮播图
	private LinearLayout lunboLayout;
	private ViewGroup lunboViewGroup;
	private ViewPager lunboViewpager;
	private ImageView[] lunboImageViews;
	private List<String> lunboImages = new ArrayList<String>();
	private int lunboCurrentItem = 0; // 当前图片下标
	private List<MobileIndexJSON> lunboMobileIndexJSONs = new ArrayList<MobileIndexJSON>();
	private GestureDetector lunboGestureDetector;
	private LinearLayout tuijianLayout;
	private List<MobileIndexJSON> tuijianMobileIndexJSONs = new ArrayList<MobileIndexJSON>();
	private ImageView[] tuijianImageViews;
	private List<String> tuijianImages = new ArrayList<String>();
//	private String referer; //来自那个链接
	private Intent intent;
	private ScheduledExecutorService scheduledExecutorService;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message message) {
			hotViewpager.setCurrentItem(hotCurrentItem);// 切换当前显示的图片
			lunboViewpager.setCurrentItem(lunboCurrentItem);
			if (productJSONs != null && !productJSONs.isEmpty()) {
				ProductJSON productJSON = productJSONs.get(hotCurrentItem);
				if (productJSON != null) {
					promotionPriceTxt.setText(Constants.CURRENCY_SYMBOL+String.valueOf(productJSON.getPrice()));
					priceTxt.setText(Constants.CURRENCY_SYMBOL+String.valueOf(productJSON.getPrice()));
					productNameTxt.setText(productJSON.getName());
				}
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_index);
		init();
	}
	
	private void init() {
		hotViewpager = (ViewPager)findViewById(R.id.index_viewpager_hot);
		hotViewGroup = (ViewGroup)findViewById(R.id.index_viewgroup_hot);
		promotionPriceTxt = (TextView)findViewById(R.id.index_promotionPrice);
		priceTxt = (TextView)findViewById(R.id.index_price);
		productNameTxt = (TextView)findViewById(R.id.index_product_name);
		teamLayout = (LinearLayout)findViewById(R.id.index_linearlayout_team);
		aboutLayout = (LinearLayout)findViewById(R.id.index_linearlayout_about);
		newsLayout = (LinearLayout)findViewById(R.id.index_linearlayout_news);
		newsTxt = (TextView)findViewById(R.id.index_text_news);
		lunboLayout = (LinearLayout)findViewById(R.id.index_linearlayout_lunbo);
		lunboViewpager = (ViewPager)findViewById(R.id.index_viewpager_lunbo);
		lunboViewGroup = (ViewGroup)findViewById(R.id.index_viewgroup_lunbo);
		tuijianLayout = (LinearLayout)findViewById(R.id.index_linearlayout_tuijian);
		
		priceTxt.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //加删除线
		teamLayout.setOnClickListener(this);
		aboutLayout.setOnClickListener(this);
		newsLayout.setOnClickListener(this);
		lunboLayout.setOnClickListener(this);
		
		String toutiao = (String)SPUtils.get(getApplicationContext(), "toutiao", getResources().getString(R.string.index_text_news));
		newsTxt.setText(toutiao);
		mobileIndexListJSON = mobileIndexService.getMobileIndex(getApplicationContext(), "IndexActivity", MobileIndexJSON.MOBILEINDEX_HOT_TYPE);
		if (mobileIndexListJSON != null && mobileIndexListJSON.getRecordList() != null && !mobileIndexListJSON.getRecordList().isEmpty()) {
			for (MobileIndexJSON mobileIndexJSON : mobileIndexListJSON.getRecordList()) {
				ProductJSON productJSON = productService.getProductDetail(getApplicationContext(), mobileIndexJSON.getProductId());
				if (productJSON.getImageUrl() == null || productJSON.getImageUrl().equals("")) continue;
				productJSONs.add(productJSON);
				hotLunboImages.add(productJSON.getImageUrl());
			}
		}
		int num = hotLunboImages.size();
		hotImageViews = new ImageView[num];
		for (int i = 0; i < num; i++) {
			hotImageViews[i] = new ImageView(this);
			hotImageViews[i].setLayoutParams(new LayoutParams(20, LayoutParams.MATCH_PARENT));
			hotImageViews[i].setPadding(40, 0, 40, 0);
			hotViewGroup.addView(hotImageViews[i]);
		}
		hotViewpager.setAdapter(new BannerAdapter(getApplicationContext(), hotLunboImages));
		hotViewpager.setOnPageChangeListener(new HotPageChangeListener());
		hotGestureDetector = new GestureDetector(getApplicationContext(), new HotGestureDetector());
		hotViewpager.setOnTouchListener(new View.OnTouchListener() {
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				hotGestureDetector.onTouchEvent(event);
				return false;
			}
		});
		
		mobileIndexListJSON = mobileIndexService.getMobileIndex(getApplicationContext(), "IndexActivity", MobileIndexJSON.MOBILEINDEX_LUNBO_TYPE);
		if (mobileIndexListJSON != null && mobileIndexListJSON.getRecordList() != null && !mobileIndexListJSON.getRecordList().isEmpty()) {
			for (MobileIndexJSON mobileIndexJSON : mobileIndexListJSON.getRecordList()) {
				if (mobileIndexJSON.getSource() == null || mobileIndexJSON.getSource().equals("")) continue;
				lunboMobileIndexJSONs.add(mobileIndexJSON);
				lunboImages.add(mobileIndexJSON.getSource());
			}
		}
		int lunboNum = lunboImages.size();
		lunboImageViews = new ImageView[lunboNum];
		for (int i = 0; i < lunboNum; i++) {
			lunboImageViews[i] = new ImageView(this);
			lunboImageViews[i].setLayoutParams(new LayoutParams(20, LayoutParams.MATCH_PARENT));
			lunboImageViews[i].setPadding(40, 0, 40, 0);
//			if (i == 0) {
//				lunboImageViews[i].setBackgroundResource(R.drawable.dotchecked);
//			} else {
//				lunboImageViews[i].setBackgroundResource(R.drawable.dotdefault);
//			}
			lunboViewGroup.addView(lunboImageViews[i]);
		}
		lunboViewpager.setAdapter(new BannerAdapter(getApplicationContext(), lunboImages));
		lunboViewpager.setOnPageChangeListener(new LunboPageChangeListener());
		lunboGestureDetector = new GestureDetector(getApplicationContext(), new LunboGestureDetector());
		lunboViewpager.setOnTouchListener(new View.OnTouchListener() {
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				lunboGestureDetector.onTouchEvent(event);
				return false;
			}
		});
		
		mobileIndexListJSON = mobileIndexService.getMobileIndex(getApplicationContext(), "IndexActivity", MobileIndexJSON.MOBILEINDEX_TUIJIAN_TYPE);
		if (mobileIndexListJSON != null && mobileIndexListJSON.getRecordList() != null && !mobileIndexListJSON.getRecordList().isEmpty()) {
			for (MobileIndexJSON mobileIndexJSON : mobileIndexListJSON.getRecordList()) {
				if (mobileIndexJSON.getSource() == null || mobileIndexJSON.getSource().equals("")) continue;
				tuijianMobileIndexJSONs.add(mobileIndexJSON);
				tuijianImages.add(mobileIndexJSON.getSource());
			}
		}
		int tuijianNum = tuijianImages.size();
		tuijianImageViews = new ImageView[tuijianNum];
		for (int i = 0; i < tuijianNum; i++) {
			tuijianImageViews[i] = new ImageView(this);
			tuijianImageViews[i].setImageBitmap(HttpUtils.returnBitMap(tuijianImages.get(i)));
			tuijianImageViews[i].setLayoutParams(new LayoutParams(160, LayoutParams.MATCH_PARENT));
			tuijianLayout.addView(tuijianImageViews[i]);
		}
		tuijianLayout.setOnClickListener(this);
		
		AppConnect.getInstance(this).setCrashReport(true);
		AppConnect.getInstance(this).initUninstallAd(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.index_linearlayout_team:
			
			break;
		case R.id.index_linearlayout_about:
			
			break;
		case R.id.index_linearlayout_news:
			
			break;
		case R.id.index_linearlayout_lunbo:
			
			break;
		case R.id.index_linearlayout_tuijian:
			intent = new Intent(IndexActivity.this, ProductListActivity.class);
			intent.putExtra("referer", "IndexActivity");
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2, TimeUnit.SECONDS);
		super.onStart();
	}
	
	/**
	 * 换行切换任务
	 */
	private class ScrollTask implements Runnable {
		@Override
		public void run() {
			synchronized (hotViewpager) {
				hotCurrentItem = (hotCurrentItem + 1) % hotImageViews.length;
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
			synchronized (lunboViewpager) {
				lunboCurrentItem = (lunboCurrentItem + 1) % lunboImageViews.length;
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			AppConnect.getInstance(this).close();
			IndexActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(IndexActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}
	
	public class HotPageChangeListener implements OnPageChangeListener {
		@SuppressWarnings("unused")
		private int oldPosition = 0;
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int position) {
			hotCurrentItem = position;
//			hotImageViews[position].setBackgroundResource(R.drawable.dotchecked);
//			hotImageViews[oldPosition].setBackgroundResource(R.drawable.dotdefault);
			oldPosition = position;
		}
	}
	
	public class LunboPageChangeListener implements OnPageChangeListener {
		@SuppressWarnings("unused")
		private int oldPosition = 0;
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int position) {
			lunboCurrentItem = position;
//			lunboImageViews[position].setBackgroundResource(R.drawable.dotchecked);
//			lunboImageViews[oldPosition].setBackgroundResource(R.drawable.dotdefault);
			oldPosition = position;
		}
	}
	
	public class HotGestureDetector extends GestureDetector.SimpleOnGestureListener {
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			if (productJSONs != null && !productJSONs.isEmpty()) {
				ProductJSON productJSON = productJSONs.get(hotCurrentItem);
				if (productJSON != null) {
					intent = new Intent(IndexActivity.this, ProductDetailActivity.class);
					intent.putExtra("productId", productJSON.getProductId());
					intent.putExtra("referer", "IndexActivity");
					startActivity(intent);
				}
			}
			return super.onSingleTapConfirmed(e);
		}
	}
	
	public class LunboGestureDetector extends GestureDetector.SimpleOnGestureListener {
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			intent = new Intent(IndexActivity.this, ProductListActivity.class);
			intent.putExtra("referer", "IndexActivity");
			startActivity(intent);
			return super.onSingleTapConfirmed(e);
		}
	}
}
